import codecs
import re
import random

from user.models import UserModel
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import UserModel
def generate_random_username(length):
    letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    numbers = '0123456789'
    username = ''.join(random.choices(letters + numbers, k=length))
    return username


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        # Add custom claims
        token['username'] = str(user.username)
        token["avatar"]=str(user.avatar)
        # ...
        return token


    def validate(self, attrs):
        # 调用父类的validate方法
        data = super().validate(attrs)

        # 获取用户对象
        user = self.user

        # 获取refresh_token
        refresh = self.get_token(user)

        # 使用refresh_token获取access_token
        access = refresh.access_token

        # 将access_token添加到响应数据中
        data['access'] = str(access)

        return data

class RegisterSerializer(serializers.ModelSerializer):
    smsCode = serializers.CharField(max_length=16,required=True,write_only = True,min_length=4)
    token=serializers.CharField(read_only=True)
    refresh = serializers.CharField(read_only=True)
    class Meta:
        model = UserModel
        fields = ['mobile','smsCode',"password","token","refresh"]
        extra_kwargs = {
            'mobile':{
                'required':True,
                "write_only":True,
                'min_length':11,
                'max_length':11
            },
            "password":{
                "required":True,
                "write_only":True,
                "min_length":6,
                "max_length":16
            }
        }
    def validate(self, attrs):
        mobile = attrs.get('mobile',None)
        password = attrs.get('password')
        sms_code = attrs.get('smsCode')
        if not re.match (r"^1[3-9]\d{9}$",mobile):
            raise serializers.ValidationError("手机号格式错误")
        print("手机号校验通过")
        redis =get_redis_connection("sms_code")
        code = redis.get(f"sms_{mobile}")
        print("redis中保存的验证码:",code)
        if code == None:
            raise serializers.ValidationError("验证码已过期")
        if code.decode() !=sms_code:
            raise serializers.ValidationError("验证码错误")

        redis.delete(f'sms_{mobile}')
        print("验证码校验通过")
#         判断用户是否存在在数据库
        try:
            UserModel.objects.get(mobile__exact=mobile)
            raise serializers.ValidationError("用户已存在")
        except UserModel.DoesNotExist:
            print("用户不存在数据库，可以注册")
        attrs.pop("smsCode")
        return attrs
    def create(self, validated_data):
        mobile =validated_data.get("mobile")
        password = validated_data.get("password")
        user = UserModel.objects.create_user(
            username=generate_random_username(6),
            mobile = mobile,
            password=password,
            nikename = UserModel.generate_nikename(),
            avatar = "avatar/1.jpg"
        )
        refresh =CustomTokenObtainPairSerializer.get_token(user = user)
        user.refresh = str(refresh)
        user.token = str(refresh.access_token)
        return user
class Userseriali(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields="__all__"

